package com.ouroboroswiki.core.content;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ouroboroswiki.core.AbstractContentRepositoryProxy;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.ContentRepository;
import com.ouroboroswiki.core.ContentUtil;
import com.ouroboroswiki.core.Version;
import com.ouroboroswiki.core.VersionBuilder;

public class BasePathModifyingContentRepositoryProxy extends
		AbstractContentRepositoryProxy {
	
	private String format;
	
	public BasePathModifyingContentRepositoryProxy( ContentRepository proxied, String format ) {
		this.proxied = proxied;
		this.format = format;
	}

	@Override
	public Version buildVersion(Object principal, ContentPath path,
			String[] versionPath, VersionBuilder versionBuilder)
			throws ContentException {
		return proxied.buildVersion(principal, adjustContentPath(path), versionPath, versionBuilder);
	}

	@Override
	public boolean exists(Object principal, ContentPath path)
			throws ContentException {
		return proxied.exists(principal, adjustContentPath(path));
	}

	@Override
	public Content getContent(Object principal, ContentPath path,
			Version version, Map<String, Object> properties)
			throws ContentException {
		return proxied.getContent(principal, adjustContentPath(path), version, properties);
	}

	private ContentPath adjustContentPath( ContentPath path ) {
		ArrayList<ContentPath> splits = ContentUtil.split(path);
		for( int i=0; i<splits.size(); i++ ) {
			ArrayList<ContentPath> paths = new ArrayList<ContentPath>();
			ContentPath split = splits.get(i);
			while( split != null ) {
				paths.add( split );
				split = split.getOnlyChild();
			}
			ContentPath base = paths.get( paths.size() - 1 );
			ContentPath result = new ContentPath( 
					String.format(this.format, base.getName()), 
					(List<ContentPath>)null, 
					base.isContextualBreak() 
			);
			for( int j=paths.size()-1; j>0; ) {
				j--;
				ContentPath section = paths.get( j );
				result = new ContentPath( section.getName(), result, section.isContextualBreak() );
			}
			splits.set(i, result);
		}
		return ContentUtil.mergeToPath(splits);
	}

}
